<?php

namespace IDock\Insurance\ACIC\Response\NonCar;

use IDock\Http\Response;
use IDock\Insurance\ACIC\Response\AllACICResponse;
use IDock\Printer\EPolicyDownloadPrinter;

class NonCarEPolicyDownResponse extends AllACICResponse
{

    /**
     * @var EPolicyDownloadPrinter $printer
     */
    public $printer;

    public function resolve(): Response
    {
        $body = $this->getBody();

        if ($body) {
            libxml_disable_entity_loader(false);
            $body = simplexml_load_string($body);

            $body = $this->objectToArray($body);

            var_dump($body);

            $errorCode = $body['Head']['ErrorCode'] ?? '';

            if ($errorCode !== '0000') {

                $errorMessage = $body['Head']['ErrorMessage'] ?? '未知错误';

                if (preg_match('/正在生成中/', $errorMessage)) {
                    $EPolicyDownloadPrinter = new EPolicyDownloadPrinter();
                    $EPolicyDownloadPrinter->doing = true;
                    $EPolicyDownloadPrinter->finish = false;
                    $this->printer = $EPolicyDownloadPrinter;
                } else {
                    $this->setError($errorMessage);
                }

                return $this;
            }

            $this->setBody($body['Body'] ?? '');
        }
        return $this;
    }

    public function printerInit(): Response
    {
        if ($this->printer) {
            return $this;
        }

        $EPolicyDownloadPrinter = new EPolicyDownloadPrinter();
        $EPolicyDownloadPrinter->finish = !$this->getError();
        $EPolicyDownloadPrinter->doing = false;
        $EPolicyDownloadPrinter->url = $this->get('Url');

        $this->printer = $EPolicyDownloadPrinter;
        return $this;
    }
}
